import {defineStore} from 'pinia'
import {showModal, toast} from "@/utils/useLayer";
import {removeToken, setToken} from "@/utils/useAccess";
import {useRouter} from "vue-router";
import type {FormInstance, FormRules} from "element-plus";
import service from "@/utils/useRequest";
import {SwitchButton} from "@element-plus/icons-vue";

export const useLoginStore = defineStore(
    'login',
    () => {
        const isLoading = ref(false)
        const router = useRouter();

        const loginFormRef = ref<FormInstance>()
        const loginFormModel = ref({
            username: "",
            password: "",
            verifyStatus: ""
        })
        const checkVerifyStatus = (rule: any, value: any, callback: any) => {
            if (!value) {
                callback(new Error('请先完成验证'))
            }
            if (value !== 'success') {
                callback(new Error('验证失败, 请重试'))
            } else {
                callback()
            }
        }
        const loginFormRules = ref<FormRules<typeof loginFormModel>>({
            username: [
                {type: 'string', required: true, message: '请输入用户名', trigger: 'blur'},
                {min: 5, max: 12, message: '用户名长度为5-12位', trigger: 'blur'}
            ],
            password: [
                {type: 'string', required: true, message: '请输入密码', trigger: 'blur'}
            ],
            verifyStatus: [
                {validator: checkVerifyStatus, require: true, trigger: 'change'}
            ]
        })

        const handleSliderVerifySuccess = (e) => loginFormModel.value.verifyStatus = e


        const submitLoginForm = async (FormEl: FormInstance | undefined) => {
            if (!FormEl) return

            await FormEl.validate(async (valid: boolean) => {
                if (!valid) return
                else {
                    const res = await service.request({
                        url: '/permission/getUserRole',
                        method: 'POST',
                        data: loginFormModel.value
                    })
                    if (res.data.status === 200) {
                        setToken(res.data.data.token)

                        toast(`${res.data.message}<br>欢迎回来:&nbsp;${loginFormModel.value.username}`)

                        await router.push('/')

                    } else {
                        toast(res.data.message, 'error')
                    }
                }
            })
        }


        const removeTheLoginState = () => {
            // 移除登录态 token
            removeToken()
            // TODO: 清除pinia存储的用户信息

        }

        const handleLogout = () => {
            showModal("是否退出登录？", "温馨提示", 'warning', markRaw(SwitchButton), true)
                .then(async () => {
                    // await logoutApi()
                    removeTheLoginState()
                    //
                    await router.push('/login')
                })
                .catch((err) => {
                    console.log(err)
                })
        }

        return {
            isLoading,
            loginFormRef,
            loginFormModel,
            loginFormRules,
            handleSliderVerifySuccess,
            submitLoginForm,
            handleLogout
        }
    })
